package cn.yunhe.control;

import cn.yunhe.entity.Topic;
import cn.yunhe.server.TopicServer;
import cn.yunhe.util.JasonUtil;
import cn.yunhe.util.PageLimitUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/FuzzySelectTopicByKeywordCurrPageServlet")
public class FuzzySelectTopicByKeywordCurrPageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String keyword = request.getParameter("keyword");
        int pageIndex = Integer.parseInt(request.getParameter("currPage"));

        TopicServer topicServer = new TopicServer();
        int totalRow = topicServer.countBykeyword(keyword); //获取标题包含keyword的总行数
        int totalPage = PageLimitUtil.getTotalePage(totalRow); //获取总页数
        int pageSize = PageLimitUtil.getPAGESIZE(); //获取每页最大行数
        int currPageIndex = PageLimitUtil.getPageIndex(pageIndex,totalPage); //获取当前页面索引,防止页码越界
        int currPage = (currPageIndex-1)*pageSize;  //获取当前页

        List<Topic> list = topicServer.FuzzySelectTopicByKeywordCurrPageServlet(keyword,currPage,pageSize);
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("totalPage",totalPage);
        map.put("currPageIndex",currPageIndex);
        map.put("list",list);
        JasonUtil.getJson(response,map);  //输出字符串
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
